package scm.inventoryControl.managedbean;

import commonInfrastructure.accountManagement.entity.WarehousePersonnelEntity;
import commonInfrastructure.accountManagement.session.WarehousePersonnelSessionBean;
import java.io.IOException;
import scm.inventoryControl.session.stateless.InventoryControlSessionBean;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpServletRequest;
import scm.inventoryControl.entity.ProductBatchRecordEntity;

@ManagedBean
@ViewScoped
public class ViewProductBatchRecordsManagedBean implements Serializable {

    @EJB
    private InventoryControlSessionBean inventorySessionBean;
    private ProductBatchRecordEntity selectedBatch;
    private boolean canDelete;
    
    @EJB
    private WarehousePersonnelSessionBean warehouseSession;

    public ViewProductBatchRecordsManagedBean() {
        warehouseSession = new WarehousePersonnelSessionBean();
    }

    public void initView(PhaseEvent event) {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        Long loginId = (Long) request.getSession().getAttribute("userId");
        WarehousePersonnelEntity user = warehouseSession.getWarehousemanById(loginId);
        if (user.getWarehouseLevel().equals("Warehouse Manager")){
            canDelete = true;
        }
        else{
            canDelete = false;
        }
    }
    
    public List<ProductBatchRecordEntity> getProductRecords() {
        return inventorySessionBean.getAllProductRecords();
    }

    public void deleteRecord(ActionEvent e) throws IOException {
        for (int i = 0; i < getProductRecords().size(); i++) {
            if (getProductRecords().get(i).getProductInventoryLevel().getProduct().getProductName().equals(selectedBatch.getProductInventoryLevel().getProduct().getProductName())
                    && getProductRecords().get(i).getManufactureDate().equals(selectedBatch.getManufactureDate())) {
                inventorySessionBean.deleteRecord(selectedBatch);
            }
        }
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Record has been deleted successfully.", ""));

    }

    public ProductBatchRecordEntity getSelectedBatch() {
        return selectedBatch;
    }

    public void setSelectedBatch(ProductBatchRecordEntity selectedBatch) {
        this.selectedBatch = selectedBatch;
    }

    /**
     * @return the canDelete
     */
    public boolean isCanDelete() {
        return canDelete;
    }

    /**
     * @param canDelete the canDelete to set
     */
    public void setCanDelete(boolean canDelete) {
        this.canDelete = canDelete;
    }
}
